<template>
  <div class="form">
    <a-form ref="formRef" :model="libraryForm" layout="vertical" @submit-success="submit">
      <!-- <a-form-item label="t['素材模式']" required field="type">
        <a-radio-group v-model="libraryForm.mode" :options="modeOption"> </a-radio-group>
      </a-form-item> -->
      <a-form-item :label="t['素材类型']" required field="type">
        <a-select v-model="libraryForm.type" :options="typeOptions"> </a-select>
      </a-form-item>
      <a-form-item :label="t['素材尺寸']" field="sizeId" required>
        <a-select v-model="libraryForm.sizeId" :options="sizeOptions"></a-select>
      </a-form-item>
      <a-form-item :label="t['素材分类']" field="word">
        <a-select v-model="libraryForm.word" :options="libraryCategoryOptions"></a-select>
      </a-form-item>
      <a-form-item :label="t['素材上传']" field="uri">
        <a-upload
          v-model:file-list="fileList"
          :auto-upload="false"
          draggable
          :disabled="!libraryForm.sizeId"
          :limit="1"
          :accept="accept()"
          @change="setUri"
        ></a-upload>
        <input v-model="libraryForm.uri" hidden />
      </a-form-item>
      <a-form-item v-if="libraryForm.type === '1' && libraryForm.cover" :label="t['素材封面']">
        <img :src="libraryForm.cover" height="120" />
      </a-form-item>
      <a-form-item :label="t['素材名称']" required field="name">
        <a-input v-model="libraryForm.name"></a-input>
      </a-form-item>
      <a-form-item :label="t['是否共享']" required field="share">
        <a-radio-group
          v-model="libraryForm.share"
          :options="translateOptions(isList)"
        ></a-radio-group>
      </a-form-item>

      <a-button type="primary" html-type="submit" :loading="loading">{{ t["保存"] }}</a-button>
    </a-form>

    <canvas id="canvas" style="display: none" width="320" height="240"></canvas>
  </div>
</template>

<script setup lang="ts">
import { ossUpload, uploadToServer } from "@/api/service/utils";
import { isList } from "@/data/options/selection";

import { userStore } from "@/store/modules/user/user";
import { base64toFile } from "@/utils/file";
import { FileItem, Message } from "@arco-design/web-vue";
import { nanoid } from "nanoid";

import { listLibrary } from "../data/curd";
import { libraryForm, resetLibraryForm, showLibraryForm } from "../data/form";
import { libraryCategoryOptions, sizeOptions, typeOptions } from "../data/options";
import { librarySizeData } from "../data/table";
import { createMediaForm, updateLibraryInfo } from "./utils";

const VIDEO_LIMIT = 5 * 1024 * 1024 * 1024 * 2024;
const t = translate("公共模块");
const store = userStore();
const formRef = ref();
const loading = ref(false);
const fileList = ref<FileItem[]>([]);

const accept = () => {
  const mime: any = {
    "0": "image/*",
    "1": "video/mp4,video/avi",
    "2": ".ttf, .otf, .woff, .woff2"
  };
  return mime[libraryForm.value.type];
};

const getResolution = () => {
  return librarySizeData.value.find((e) => {
    if (e.sizeId === libraryForm.value.sizeId) {
      return e;
    }
    return null;
  });
};
const uploadFile = async (file: FileItem): Promise<string | undefined> => {
  if (!file.file) return;
  let href = "";

  if (store.$state.oss) {
    const { url } = await ossUpload({
      file: file.file,
      randomName: true,
      type: libraryForm.value.type
    });

    libraryForm.value.uri = url;

    libraryForm.value.bytes = file.file?.size || 0;
    href = url;
  } else {
    /* 上传到本地 */
    const { type } = libraryForm.value;
    const url = store.$state.paths[type];

    const { data } = await uploadToServer(`${url}`, file.file);

    if (data.code === 500) {
      loading.value = false;
      Message.warning(data.msg);
    } else {
      Message.success(data.msg);
      href = data.data;
    }
  }

  return href;
};
/* 检测资源的大小 */
const checkResource = (file: File) => {
  const sizeInfo = getResolution()!;

  return new Promise((res) => {
    if (libraryForm.value.type === "0") {
      const image = new Image();
      image.src = URL.createObjectURL(file);

      image.onload = () => {
        if (image.width === sizeInfo.width && image.height === sizeInfo.height) {
          res(true);
        }
        res(false);
      };
    } else if (libraryForm.value.type === "1") {
      if (file.size > VIDEO_LIMIT) {
        Message.warning(t.value?.["请选择小于5M的视频"]);
        res(false);
        return;
      }
      const video = document.createElement("video");
      video.src = URL.createObjectURL(file);
      video.hidden = true;
      video.muted = true;
      video.autoplay = true;
      const canvas = document.getElementById("canvas") as HTMLCanvasElement;
      const context = canvas.getContext("2d")!;

      video.addEventListener("loadeddata", async () => {
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        context.drawImage(video, 0, 0, canvas.width, canvas.height);
        const base64 = canvas.toDataURL("image/webp").replace(`data:image/webp;base64,`, "");

        const cover = base64toFile(base64, `${nanoid()}.png`);
        const limitWidth = Math.abs(video.videoWidth - sizeInfo.width) < 5;
        const limitHeight = Math.abs(video.videoHeight - sizeInfo.height) < 5;
        if (limitWidth && limitHeight) {
          const coverData = await uploadFile({
            uid: nanoid(),
            file: cover
          });
          const videoData = await uploadFile({
            uid: nanoid(),
            file
          });
          if (coverData) {
            libraryForm.value.cover = coverData;
          }
          if (videoData) {
            libraryForm.value.uri = videoData;
          }
        }
      });

      video.onloadedmetadata = () => {
        const limitWidth = Math.abs(video.videoWidth - sizeInfo.width) < 5;
        const limitHeight = Math.abs(video.videoHeight - sizeInfo.height) < 5;
        if (limitWidth && limitHeight) {
          res(true);
          return;
        }
        res(false);
      };
    }
  });
};
const setUri = async () => {
  const file = fileList.value?.[0];
  libraryForm.value.cover = "";

  const result = await checkResource(file.file!);
  if (!result) {
    Message.warning(t.value?.["素材尺寸不符合要求"]);
    libraryForm.value.uri = "";
    fileList.value = [];
    return;
  }
  if (fileList.value.length === 1) {
    libraryForm.value.name = file.name || "Untitled";
    libraryForm.value.uri = nanoid(12);
  }
};

const submit = async () => {
  try {
    loading.value = true;
    if (libraryForm.value.resId) {
      await updateLibraryInfo();
    } else {
      const file = fileList.value?.[0];
      await createMediaForm(file);
    }

    loading.value = false;
    await listLibrary();

    showLibraryForm.value = !showLibraryForm.value;
  } catch (error) {
    loading.value = false;
  }
};
watch(showLibraryForm, (v) => {
  if (!v) {
    resetLibraryForm();
    formRef.value?.resetFields();
    fileList.value = [];
  }
});
</script>

<style lang="scss" scoped></style>
